<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告标语 -->
      <el-alert title="注意:只允许为第三级分类设置相关参数!" type="warning" show-icon></el-alert>
      <!-- 选择商品分类 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类: </span>
          <!-- 级联选择器 -->
          <el-cascader
            v-model="selectCategorKeys"
            :options="storGoodsCategory"
            :props="goodsCategoryProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab标签 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 动态参数按钮 -->
          <el-button
            type="primary"
            size="mini"
            @click="addParamsVisible=true"
            :disabled="isBtnDisabled"
          >动态参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 标签 -->
                <el-tag closable v-for="(item,i) in scope.row.attr_vals"
                 :key="i" @close="delParams(scope.row,i)">{{item}}</el-tag>
                <!-- 文本框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue" ref="saveTagInputRef" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)" >
                </el-input>
                <!-- 按钮 -->
                <el-button v-else class="button-new-tag"
                 size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="delParamsClick(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            @click="addParamsVisible=true"
            :disabled="isBtnDisabled"
          >静态属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
             <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 标签 -->
                <el-tag closable v-for="(item,i) in scope.row.attr_vals"
                 :key="i" @close="delParams(scope.row,i)">{{item}}</el-tag>
                <!-- 文本框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue" ref="saveTagInputRef" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)" >
                </el-input>
                <!-- 按钮 -->
                <el-button v-else class="button-new-tag"
                 size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="delParamsClick(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加静动态对话框 -->
    <el-dialog :title="'添加'+ titleText" :visible.sync="addParamsVisible"
      width="50%" @close="addParamsClose" >
      <el-form :model="addParamsForm" :rules="addParamsRules"
        ref="addParamsRef" label-width="100px" >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑静动态对话框 -->
    <el-dialog :title="'编辑'+ titleText" :visible.sync="showEditVisible"
      width="50%" @close="showEditClose" >
      <el-form :model="showEditForm" :rules="addParamsRules"
        ref="showEditRef" label-width="100px" >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="showEditForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="showEdit(showEditForm.attr_id)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 存储商品分类
      storGoodsCategory: [],
      // 级联选择器的配置选项
      goodsCategoryProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 级联选择框双向绑定到的数组
      selectCategorKeys: [],
      // tab标签的双向绑定
      activeName: 'many',
      // 动态参数
      manyTableData: [],
      // 静态属性
      onlyTableData: [],
      // 静动态对话框显示隐藏
      addParamsVisible: false,
      // 校验规则
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 静动态对话框表单双向绑定数据
      addParamsForm: {
        attr_name: ''
      },
      // 编辑静动态对话框显示隐藏
      showEditVisible: false,
      // 编辑静动态对话框表单双向绑定数据
      showEditForm: {}
    }
  },
  created () {
    this.getGoodsCategory()
  },
  methods: {
    // 获取商品分类列表
    async getGoodsCategory () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.storGoodsCategory = res.data
      console.log(this.storGoodsCategory)
    },
    // 级联选择框中的值发生变化时触发这个函数
    handleChange () {
      if (this.selectCategorKeys.length !== 3) {
        this.selectCategorKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      console.log(this.selectCategorKeys)
      this.getParamsData()
    },
    // tab标签点击事件
    handleClick () {
      console.log(this.activeName)
      this.getParamsData()
    },
    // 获取参数的列表数据
    async getParamsData () {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })

      if (this.activeName === 'many') {
        this.manyTableData = res.data
        console.log(this.manyTableData)
      } else {
        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    // 静动态表单重置
    addParamsClose () {
      this.$refs.addParamsRef.resetFields()
    },
    // 添加参数
    addParams () {
      this.$refs.addParamsRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加参数成功')
        this.addParamsVisible = false
        this.getParamsData()
      })
    },
    // 编辑按钮
    async showEditDialog (id) {
      this.showEditVisible = true
      console.log(id)

      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/` + id,
        {
          attr_sel: this.activeName
        }
      )
      this.showEditForm = res.data

      // this.showEditForm = res.data
    },
    // 编辑表单重置
    showEditClose () {
      this.$refs.showEditRef.resetFields()
    },
    // 提交编辑
    showEdit (id) {
      this.$refs.showEditRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/` + id, {
            attr_name: this.showEditForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新失败')
        }
        this.$message.success('更新成功')
        this.showEditVisible = false
        this.getParamsData()
      })
    },
    // 删除弹框
    async delParamsClick (id) {
      const confirmMessage = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (confirmMessage !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/` + id
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getParamsData()
    },
    // 按下键盘 Enter 或者失去焦点时触发
    handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      this.saveParams(row)
    },
    // 删除对应的参数可选项
    delParams (row, i) {
      row.attr_vals.splice(i, 1)
      this.saveParams(row)
    },
    // 保存参数功能
    async saveParams (row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新失败')
      }
      this.$message.success('更新成功')
    },
    // 点击事件
    showInput (row) {
      row.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick 方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInputRef.$refs.input.focus()
      })
    }
  },
  //
  computed: {
    // 判断按钮是否禁用
    isBtnDisabled () {
      if (this.selectCategorKeys.length !== 3) {
        return true
      }
      return false
    },
    // 获取参数的列表id
    cateId () {
      if (this.selectCategorKeys.length === 3) {
        return this.selectCategorKeys[2]
      }
      return null
    },
    //
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px;
}
.el-tag{
  margin: 10px;
}
.input-new-tag{
  width: 100px;
}
</style>
